//
//  HDFounctionBaseController.swift
//  Wmsmobile
//
//  Created by xuNick on 16/9/9.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit

let HDFSectionHeadrHeight: CGFloat = 40

class HDFounctionBaseController: UITableViewController , UIGestureRecognizerDelegate {

    //MARK: - property
    var cellsDict = [String : HDFounctionBaseCell]()
    var reuseFlag: Bool = true
    var downloadData = [String : String]() // 用于保存每次下载的数据
    var bottomTitles: [String] = [String]()
    var activedCell: HDInputViewStateProtocol?
    var model: YunCangModel?
    var firstActiveIndexPath: IndexPath?
    weak var savedGestureRecognizerDelegate:UIGestureRecognizerDelegate?
    
    lazy fileprivate var favoriteButton:UIButton = {
        let button = UIButton(frame: CGRect(x: KscreenWidth - 54, y: 0, width: 44, height: 44))
        button.setImage(UIImage(named: "收藏home"), for: UIControlState())
        button.setImage(UIImage(named: "收藏icon"), for: UIControlState.selected)
        return button
    }()
    //MARK: - lifecycle
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nil, bundle: nil)
    }
    init(){
        super.init(style: UITableViewStyle.grouped)
//        let classname = NSStringFromClass(self.Type)
       let classname = NSStringFromClass(self.classForCoder)
        //计算对应的字符串
        let string1 = classname.components(separatedBy: ".").last
        let stirng2 = string1?.components(separatedBy: "Controller").first
        let result = stirng2?.replacingOccurrences(of: "_", with: ".")
        for item in (userInfo?.mainMenuDataArray)! {
            for model in item {
                if result == model.FCLASSNAME {
                    self.model = model
                    return
                }
            }
        }
        //取得对应的model
    }
    override func viewDidLoad() {
        let leftItem = UIBarButtonItem(image: UIImage(named: "返回"), landscapeImagePhone: UIImage(named: "返回"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(HDFounctionBaseController.clickReturnButton(_:)))
        self.navigationItem.leftBarButtonItem = leftItem
//        let tap = UITapGestureRecognizer(target: self, action: #selector(HDFounctionBaseController.tapOnTableView))//添加点击回收键盘的tap手势
//        self.tableView.addGestureRecognizer(tap)
        self.tableView.rowHeight = 44
        self.navigationItem.title = model?.FCAPTION
        self.tableView.allowsSelection = false
        self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        self.favoriteButton.addTarget(self, action: #selector(HDFounctionBaseController.clickFavoriteButton(_:)), for: UIControlEvents.touchUpInside)
        self.navigationController?.navigationBar.addSubview(favoriteButton)
        //        self.navigationItem.rightBarButtonItem = favoriteBarButton
        self.favoriteButton.isSelected = self.model?.FAVORITES == NSNumber.init(value: 1 as Int) ? true : false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        savedGestureRecognizerDelegate = self.navigationController?.interactivePopGestureRecognizer?.delegate
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    }
    override func viewWillDisappear(_ animated: Bool) {
        self.view.endEditing(true)
//        let childControllers = self.navigationController?.viewControllers
//        if let _ = childControllers!.indexOf(self) {
//        }else{
//            favoriteButton.removeFromSuperview()
//        }
        favoriteButton.removeFromSuperview()
        HDShowMessageManager.sharedManager.messageView?.removeFromSuperview()
        HDShowMessageManager.sharedManager.messageView = nil
        self.navigationController?.interactivePopGestureRecognizer?.delegate = savedGestureRecognizerDelegate
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if let cell = self.tableView.cellForRow(at: firstActiveIndexPath ?? IndexPath(item: -1, section: 0)) as? HDInputViewStateProtocol {
            cell.state = inputViewState.activated
        }
    }
    //MARK: - private
    func clickFavoriteButton(_ button: UIButton){
        self.favoriteButton.isSelected = !self.favoriteButton.isSelected
        self.favoriteButton.isEnabled = false
        NetworkTool.sharedTools.postSoap(["piModule" : self.model!.FMODULENO! , "piFlag" : self.favoriteButton.isSelected ? "1" : "0" , "piOperator" : (userInfo?.userName)!], bodyMethod: "UpdUserUsedModule", suffix: "225", success: { [weak self] (data) in
            //添加成功
            if self!.favoriteButton.isSelected {  //添加收藏
                userInfo?.favoriteItems?.append(self!.model!)
                self!.model?.FAVORITES = NSNumber.init(value: 1 as Int)
                self!.showMessage("添加收藏成功", success: true)
            }else{ //取消收藏
                self!.showMessage("取消收藏成功", success: true)
                self!.model?.FAVORITES = NSNumber.init(value: 0 as Int)
                var indexToUpdate: Int?
                for i in 00..<(userInfo?.favoriteItems)!.count {
                    if (userInfo?.favoriteItems)![i] == self!.model {
                        indexToUpdate = i
                    }
                }
                userInfo?.favoriteItems?.remove(at: indexToUpdate!)
            }
            self!.favoriteButton.isEnabled = true
        }) {
            //添加失败
            if self.favoriteButton.isSelected {
                self.showMessage("添加收藏失败", success: false)
                self.favoriteButton.isSelected = false
            }else{
                self.showMessage("取消收藏失败", success: false)
                self.favoriteButton.isSelected = true
            }
            self.favoriteButton.isEnabled = true
        }
    }
    //MARK: - delegate
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
            return false
        }
        return true
    }
    //MARK: - public
    
    func getText(_ item: Int, inSection: Int) -> (String?){
        let cell = self.cellsDict[String(describing: IndexPath(item: item, section: inSection))] as! HDgetAndSetProtocol
        return cell.getText()
    }
    func setText(_ item: Int, inSection: Int, text:String?){
        let cell = self.cellsDict[String(describing: IndexPath(item: item, section: inSection))] as! HDgetAndSetProtocol
        cell.SetText(text)
    }
    func showAlert(_ title: String, message: String , actionLTitle: String, actionRTitle: String? , clickLeft:@escaping () -> () , clickRight: (() -> ())?){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: actionLTitle, style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
            clickLeft()
           
        }))
        if let rightClosure = clickRight{
            alertController.addAction(UIAlertAction(title: actionRTitle, style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
                rightClosure()
            }))
        }
        self.present(alertController, animated: true, completion: nil)
    }
    func clickReturnButton(_ button: UIButton){
        //如果第一个cell是空的，直接返回
            if self.isEmpty() {
                _ = self.navigationController?.popViewController(animated: true)
                return
        }
        
        let alertController  = UIAlertController(title: "确认", message: "确定清空所有信息并退出吗？", preferredStyle: UIAlertControllerStyle.alert)
        let doneAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.default) { [weak self] (done) in
            _ = self?.navigationController?.popViewController(animated: true)
        }
        let cancleAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (cancel) in
            alertController.dismiss(animated: true, completion: nil)
        }
        alertController.addAction(cancleAction)
        alertController.addAction(doneAction)
        self.present(alertController, animated: true, completion: nil)
    }
    func isEmpty() -> (Bool){
        return true
    }
    func oneToManyHandler(_ piArticleCode : String , piOwner : String? , piBin : String? ,  success: @escaping (_ dict: [String : String]) -> () , failed: @escaping(() -> ())){
        if piOwner == nil {
            HDOneToManyHandler.GetArticleByBin(piArticleCode, piBin: piBin!, success: { (dict) in
                self.downloadData += dict
                success(dict)
                }, failed: { (dict) in
                    self.showMessage(dict["poErrMsg"]!, success: false)
                    failed()
                }, netError: {
                    self.showMessage("网络连接错误", success: false)
            })
        }else{
            HDOneToManyHandler.GetArticleByOwner(piArticleCode, piOwner: piOwner!, success: { (dict) in
                self.downloadData += dict
                success(dict)
                }, failed: { (dict) in
                    self.showMessage(dict["poErrMsg"]!, success: false)
                    failed()
                }, netError: {
                    self.showMessage("网络连接错误", success: false)
            })
        }
    }
    func getNumberByString(_ string: String , standard: String) -> (Double){ //传入“8+5” "10"得到 8 * 10 + 5 = 85
        let stringArr = string.components(separatedBy: "+")
        let StringArrStandard = standard.components(separatedBy: "*")
        let middle = StringArrStandard.count == 3 ? Double(StringArrStandard[1]) : 1.0
        let firstStan = Double(StringArrStandard.first!) ?? 1
        let lastStan = Double(StringArrStandard.last!) ?? 1
        let standsrdNum = middle! * firstStan * lastStan
        let wholeNum = Double(stringArr.first!)
        if stringArr.count == 2 {
            let singleNum = Double(stringArr.last!)
            return wholeNum! * standsrdNum + singleNum!
        }else{
            return wholeNum! * standsrdNum
        }
    }
    /**
     *cell:当前cell
     *nextitem：要跳转到的下一个cell的item值
     *nextSection：要跳转到的下一个cell的Section值
     *message：清屏后要提示的信息，输入nil不提示
     *success：成功信息和失败信息
     **/
    func resetController(_ cell: HDInputViewStateProtocol, nextItem: Int, nextSection: Int , message: String? ,success: Bool){
        self.reuseFlag = false
        self.tableView.reloadData()
        self.goNextCell(cell, nextInsexPath: IndexPath(item: nextItem, section: nextSection))
        if let msg = message{
            self.showMessage(msg, success: success)
        }
        self.reuseFlag = true
    }
    //完全初始化控制器
    func resetController() -> (HDFounctionBaseController){
        let nav = self.navigationController
        nav!.popViewController(animated: false)
         let myClass = self.classForCoder as! UITableViewController.Type
        let vc = myClass.init() as! HDFounctionBaseController
        nav!.pushViewController(vc, animated: false)
        return vc
    }
    func getData(_ params:[String : String] , bodyMethod : String , suffix: String? , success:@escaping (_ dict:[String : String]) -> () , failed : @escaping (_ dict: [String : String]) -> ()){
        NetworkTool.sharedTools.postSoap(params as NSDictionary, bodyMethod: bodyMethod, suffix: suffix, success: { (data) in
            if let dict = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "\(bodyMethod)Response").first{
                self.downloadData += dict
                if dict["\(bodyMethod)Result"] == "0" { // 请求成功
                    success(dict)
                }else{ //返回了错误信息
                    self.showMessage(self.downloadData["poErrMsg"]!, success: false)
                    failed(dict)
                }
            }
            }, failed: {
                self.showNeterror()
        })
    }
    func getCollection(_ params:[String : String] , bodyMethod : String , suffix: String? , success:@escaping (_ dict:[String : String] , _ collections: [[String : String]]) -> () , failed : @escaping () -> ()){
        NetworkTool.sharedTools.postSoap(params as NSDictionary, bodyMethod: bodyMethod, suffix: suffix, success: { (data) in
            if let dict = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "\(bodyMethod)Response").first{
                self.downloadData += dict
                if dict["\(bodyMethod)Result"] == "0" { // 请求成功
                    let array = analysisManager.shareManager2.XmlParserAnalysis(XMLParser(data: data), elementName: "collect")
                    success(dict , array)
                }else{ //返回了错误信息
                    self.showMessage(self.downloadData["poErrMsg"]!, success: false)
                    failed()
                }
            }
            }, failed: {
                self.showNeterror()
        })
    }

    func showNeterror(){
         HDShowMessageManager.sharedManager.showMessage(self, message: "网络连接异常，请检查网络", success: false)
    }
    func showMessage(_ message: String , success: Bool){
        HDShowMessageManager.sharedManager.showMessage(self, message: message, success: success)
    }
    func goNextCell(_ lastCell:HDInputViewStateProtocol ,nextInsexPath: IndexPath){
        lastCell.state = .disabled
        if let nextCell = self.tableView.cellForRow(at: nextInsexPath) as? HDInputViewStateProtocol {
            nextCell.state = inputViewState.activated
            self.activedCell = nextCell
        }else{
            self.tableView.scrollToRow(at: nextInsexPath, at: UITableViewScrollPosition.top, animated: false)
            let nextCell = self.tableView.cellForRow(at: nextInsexPath) as! HDInputViewStateProtocol
            nextCell.state = inputViewState.activated
        }
    }
    //MARK: - UIResponse
//    func tapOnTableView() {
////        self.view.endEditing(true)
//    }
    //MARK: - tableViewDelegate
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
            return nil
    }
    //MARK: - tableViewDatasource

    //MARK: - deinit
    deinit{
        print("\(self)-----------------------------销毁了")
    }
}

class viewCacheManager: NSObject {
    weak var activedTF: UITextField?
    static let shareManager: viewCacheManager  = {
        let manager = viewCacheManager()
        return manager
    }()
    override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(viewCacheManager.newEnditingBegin(_:)), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil)
    }
    func newEnditingBegin(_ notification: Notification){
        let object:UITextField = (notification.object as? UITextField)!
        self.activedTF = object
    }
    class func activedTextField() -> (UITextField?){
        return self.shareManager.activedTF
    }
}




